import 'dart:async';

import 'package:flutter/material.dart';

import '../api_repository/login_repository.dart';
import '../base/utils/nd_cache.dart';
import '../component/loading_component.dart';
import '../env_config.dart';
import '../home/main_page.dart';
import 'component/login_component.dart';
import 'domain_edit_page.dart';

///
///Author: YoungChan
///Date: 2019/8/28 11:16
///Description: 登录界面
///

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);
  static const routerName = 'LoginPage';

  static Future pushReplace(BuildContext context) =>
      Navigator.of(context).pushReplacement(MaterialPageRoute(
        settings: const RouteSettings(name: routerName),
        builder: (context) => const LoginPage(),
      ));

  static Future push(BuildContext context) =>
      Navigator.of(context).push(MaterialPageRoute(
        settings: const RouteSettings(name: routerName),
        builder: (context) => const LoginPage(),
      ));

  @override
  _LoginPageState createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {
  static final _tag = 'Login';

  var _loginRep = LoginRepository();
  final _accountFocus = FocusNode();
  final _phoneFocus = FocusNode();
  final _passwordFocus = FocusNode();

  String _versionName = '';

  bool isReleaseMode = true;
  int lastClickTime = 0; // 记录上次点击版本号时间戳
  int clickCount = 0;

  bool needPictureCheck = false;

  bool isShowingCheck = false;

  ///登录方式，true：手机号验证码；false：账号密码
  var _mobileLogin = false;

  Future _init() async {
    // if (_mobileLogin) {
    //   FocusScope.of(context).requestFocus(_phoneFocus);
    // } else {
    //   FocusScope.of(context).requestFocus(_accountFocus);
    // }

    return Future.value();
  }

  @override
  void initState() {
    _init();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///登录操作
  void _onLogin(BuildContext context, {bool forceLogin = false}) async {
    FocusScope.of(context).unfocus();
    var password = _password;
    var mobileType = _mobileLogin;
    if (!_mobileLogin) {
      //校验账号密码不能为空
      if (_account.isEmpty || _password.isEmpty) {
        toast(context, '账号密码不能为空');
        return;
      }
    }
    startLoading<NDUser?>(
      context,
      () => _doLogin(password, forceLogin: forceLogin),
      text: '登录中',
    ).then((user) async {
      toast(context, '登录成功');
      //跳转到主页面
      await pushHome(context, userInfo: user?.toJson());
    }).catchError((err) async {
      if (err.toString().startsWith('501')) {
        var split = err.toString().split(':');
        // 登录冲突 无需报错
        var confirm = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('提示'),
              content: Text('${split[1]}'),
              actions: <Widget>[
                TextButton(
                  child: Text('取消'),
                  onPressed: () {
                    // 关闭对话框
                    Navigator.of(context).pop(false);
                  },
                ),
                TextButton(
                  child: Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        );
        if (confirm == true) {
          _onLogin(context, forceLogin: true);
        }
      } else {
        toast(context, err.toString());
      }
    });
  }

  Future<NDUser> _doLogin(String password, {bool forceLogin = false}) async {
    NDUser user;
    if (!_mobileLogin) {
      user = await _loginRep.accountLogin(
          account: _account, password: password, forceLogin: forceLogin);
      //缓存输入的帐号
      NDCache.setString('login', 'account', _account);
    } else {
      user = await _loginRep.mobileLogin(
          mobile: _mobile, code: _code, forceLogin: forceLogin);
    }

    if (!_mobileLogin) {
    } else {
      NDCache.setString('MobileLoginType', 'mobile', _mobile);
    }
    return Future.value(user);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.white.withOpacity(0.1),
      body: Stack(
        children: [
          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const SizedBox(height: 90),
                _buildTitle(),
                const SizedBox(height: 38),
                AnimatedCrossFade(
                  firstChild: _buildMobileLogin(context),
                  secondChild: _buildPasswordLogin(context),
                  crossFadeState: _mobileLogin
                      ? CrossFadeState.showFirst
                      : CrossFadeState.showSecond,
                  duration: Duration(milliseconds: 250),
                ),
                const SizedBox(height: 30),
                buildLoginButton(context),
                Row(
                  children: [
                    Padding(
                      padding:
                          const EdgeInsets.only(left: 16, top: 16, bottom: 16),
                      child: InkWell(
                        onTap: () {
                          setState(() {
                            _mobileLogin = !_mobileLogin;
                            NDCache.setBool(
                                'LoginType', 'mobileLogin', _mobileLogin);
                            if (_mobileLogin) {
                              FocusScope.of(context).requestFocus(_phoneFocus);
                            } else {
                              FocusScope.of(context)
                                  .requestFocus(_accountFocus);
                            }
                          });
                        },
                        child: Text(
                          !_mobileLogin ? '手机号登录' : '账号密码登录',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.blueAccent,
                          ),
                        ),
                      ),
                    ),
                    const Spacer(),
                    buildDomainButton(context),
                  ],
                ),
                const SizedBox(height: 16),
              ],
            ),
          ),
        ],
      ),
    );
  }

  SizedBox buildLoginButton(BuildContext context) {
    return SizedBox.fromSize(
      size: Size.fromHeight(48),
      child: Padding(
        padding: EdgeInsets.only(left: 16, right: 16),
        child: FilledButton(
          onPressed: () {
            //登录
            _onLogin(context);
          },
          child: Text(
            '登录',
            style: TextStyle(fontSize: 18),
          ),
        ),
      ),
    );
  }

  Widget buildDomainButton(BuildContext context) {
    return (EnvConfig.isPrivate || EnvConfig.testMode)
        ? IconButton(
            icon: Icon(Icons.network_wifi_outlined),
            onPressed: () {
              TestDomainEditPage.push(context);
            },
          )
        : SizedBox.shrink();
  }

  var _account = '';
  var _password = '';

  ///账号密码登录
  Widget _buildPasswordLogin(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: AccountPasswordInputSection(
        account: _account,
        password: _password,
        onAccountChanged: (account) {
          _account = account;
        },
        onPasswordChanged: (password) {
          _password = password;
        },
        accountNode: _accountFocus,
        passwordNode: _passwordFocus,
        autofocus: false,
        onAccountSubmitted: (String value) {
          FocusScope.of(context).requestFocus(_passwordFocus);
        },
        onPasswordSubmitted: (String value) {
          _onLogin(context);
        },
      ),
    );
  }

  var _mobile = '';
  var _code = '';

  ///账号密码登录
  Widget _buildMobileLogin(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: MobileCodeInputSection(
        mobile: _mobile,
        code: _code,
        autofocus: false,
        mobileFocusNode: _phoneFocus,
        onSendCode: () async {
          FocusScope.of(context).unfocus();
          var success = true;
          await startLoading<bool>(
            context,
            () => _loginRep.mobileLoginSms(mobile: _mobile),
          ).catchError((err) {
            toast(context, err.toString());
            success = false;
            return null;
          });
          if (success) {
            toast(context, '发送成功');
          }
          return Future.value(success);
        },
        onMobileChanged: (mobile) {
          _mobile = mobile;
        },
        onCodeChanged: (code) {
          _code = code;
        },
      ),
    );
  }

  Widget _buildTitle() {
    return Padding(
      padding: EdgeInsets.only(left: 16),
      child: Text(
        '欢迎登录',
        style: TextStyle(
            fontSize: 24, color: Colors.black87, fontWeight: FontWeight.bold),
        textAlign: TextAlign.start,
      ),
    );
  }
}
